﻿using AntDesign;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Xms.Abp.AntDesignUI;

public static class XmsUIHelper
{
    public static TableColumnInfo[] GetTableColumnInfos(Type listModelType)
    {
        var properties = listModelType.GetProperties().Select(r => (r, r.GetCustomAttribute<UIColumnAttribute>())).Where(r => r.Item2 != null).OrderBy(r => r.Item2.Fixed == UIColumnFixedType.Left ? 1 : (r.Item2.Fixed == null ? 2 : 3)).ThenBy(r => r.Item2.Order);
        var columns = new List<TableColumnInfo>();
        foreach (var property in properties)
        {
            var columnInfo = new TableColumnInfo
            {
                Fixed = property.Item2.Fixed?.ToString()?.ToLower(),
                Align = (ColumnAlign)property.Item2.Align,
                Title = property.Item2.Title ?? property.r.Name,
                Editable = property.Item2.Editable,
                Format = property.Item2.Format,
                Name = property.r.Name,
                Icon = property.Item2.Icon,
                Sortable = property.Item2.Sortable,
                SorterMultiple = property.Item2.SorterMultiple,
                Property = property.r,
                SwitchText = property.Item2.SwitchText,
            };
            columns.Add(columnInfo);
        }
        return columns.ToArray();
    }
    public static TableColumnInfo[] GetTableColumnInfos<TListViewModel>()
    {
        return GetTableColumnInfos(typeof(TListViewModel));
    }
}

public class TableColumnInfo
{
    public string Name { get; set; }
    public string Title { get; set; }
    public bool Editable { get; set; }
    public string Fixed { get; set; }
    public bool Sortable { get; set; }
    public int SorterMultiple { get; set; }
    public ColumnAlign Align { get; set; } = ColumnAlign.Left;
    public string Icon { get; set; }
    public string Format { get; set; }
    public string SwitchText { get; set; }
    public PropertyInfo Property { get; set; }
    public string GetValue(object context)
    {
        var value = Property.GetValue(context);
        if(!Format.IsNullOrWhiteSpace() && value is IFormattable f)
        {
            return f.ToString(Format, null);
        }
        return value.ToString();
    }
    public void SetValue(object context, object value)
    {
        Property.SetValue(context, value);
    }
}
